package com.icss.ah.orderReview.action;

import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import jxl.Workbook;
import jxl.format.Colour;
import jxl.format.UnderlineStyle;
import jxl.write.Label;
import jxl.write.WritableCellFormat;
import jxl.write.WritableFont;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;

import net.sf.json.JSONObject;

import org.apache.struts2.ServletActionContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.icss.ah.base.action.BaseAction;
import com.icss.ah.base.util.DateUtils;
import com.icss.ah.login.bean.UserInfoBean;
import com.icss.ah.orderReview.service.OrderReviewService;

@Controller
@Scope("prototype")
public class OrderReviewAction extends BaseAction {

	private static final long serialVersionUID = 1234525L;
	
	@Autowired
	private OrderReviewService orderReviewService;
	
	private String conName;
	private String begTime;
	private String endTime;
	private String orderIds;
	private String status;
	
	public String toOrderReviewListPage(){
		if(begTime==null||"".equals(begTime)) begTime = DateUtils.getBursarMonth(-1);
		if(endTime==null||"".equals(endTime)) endTime = DateUtils.getCurrentDate("yyyy-MM-dd");
		request = this.getRequest();
		request.setAttribute("begTime", begTime);
		request.setAttribute("endTime", endTime);
		return "toOrderReviewListPage";
	}
	
	public void queryOrderReviewList(){
		String userCode=getUserCodeFromSession();
		UserInfoBean userInfo=getUserInfo(userCode);
		String shopId=userInfo.getShopId();
		String corpId = userInfo.getCorpId();
		Map<String, String> map = new HashMap<String, String>();
		map.put("corpId",corpId);	//公众号id
		map.put("shopId", shopId);	//商铺id
		map.put("begTime", begTime);
		map.put("endTime", endTime);
		map.put("conName", conName);
		map.put("status", status);
		map.put("startIndex", getStartIndexMysql());
		map.put("rowNums", getEndIndexMysql());
		dataGridJson = orderReviewService.queryOrderReviewList(map);
		str2Resp(JSONObject.fromObject(dataGridJson).toString());
	}
	
	public void reviewBatch(){
		Map<String, String> map = new HashMap<String, String>();
		orderIds = "'"+orderIds.replaceAll(",", "','")+"'";
		map.put("orderIds", orderIds);
		String result = orderReviewService.reviewBatch(map);
		str2Resp(result);
	}
	
	public String showDetail(){
		request = this.getRequest();
		String orderNo = request.getParameter("orderNo");
		request.setAttribute("orderNo", orderNo);
		request.setAttribute("begTime", begTime);
		request.setAttribute("endTime", endTime);
		return "showDetail";
	}
	
	public void exportOrderReviewList(){
		try {
			String userCode=getUserCodeFromSession();
			UserInfoBean userInfo=getUserInfo(userCode);
			String shopId=userInfo.getShopId();
			String corpId = userInfo.getCorpId();
			Map<String, String> map = new HashMap<String, String>();
			map.put("corpId",corpId);	//公众号id
			map.put("shopId", shopId);	//商铺id
			map.put("begTime", begTime);
			map.put("endTime", endTime);
			map.put("conName", conName);
			map.put("status", status);
			String fname = "订单复核";
			String allPara = conName+begTime+endTime+status;
			if("".equals(allPara)){
				endTime = DateUtils.getCurrentDate("yyyy-MM-dd");
				begTime = DateUtils.getBursarMonth(-1);
				fname = begTime+" ~ "+endTime+fname;
				map.put("begTime", begTime);
			}
			List<Map<String, Object>> list = orderReviewService.exportOrderReviewList(map);
			String[] colNames = {"序号","订单号","支付人","时间","订单（￥）","实付（￥）","手续费（￥）","入账（￥）","状态"};
			String[] colParas = {"ORDER_NO","CON_NAME","RECEIVING_TIME","ORDER_MONEY",
					"ORDER_REAL_MONEY","ALL_FEE_MONEY","REAL_MONEY","STATUS_NAME"};
			int [] widths = {8,30,20,15,15,15,15,15,15};
			createExcel(this.getResponse(), list, fname, colNames, colParas, widths);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public void createExcel(HttpServletResponse response,List<Map<String, Object>> list,String fname,String[] colNames,String[] colParas,int [] widths) throws WriteException,IOException{
		response.reset();//清空输出流
	    
		//下面是对中文文件名的处理
		response.setContentType("text/html;charset=utf-8");
		//请求来源浏览器的信息
		String agent = ServletActionContext.getRequest().getHeader("USER-AGENT");
		if (null != agent && -1 != agent.indexOf("Mozilla")) {// 火狐
			response.setHeader("Content-Disposition","attachment;filename="+ new String(fname.getBytes("GB2312"),"ISO-8859-1")+".xls");
        }else{
        	fname = java.net.URLEncoder.encode(fname,"UTF-8");
			response.setHeader("Content-Disposition","attachment;filename="+new String(fname.getBytes("UTF-8"),"GBK")+".xls");
        }
		response.setContentType("application/msexcel");//定义输出类型
		OutputStream os = response.getOutputStream();
		
		WritableFont wfTitle= new WritableFont(WritableFont.ARIAL,16,WritableFont.BOLD,false,UnderlineStyle.NO_UNDERLINE,Colour.BLACK);
    	WritableCellFormat wcfTitle= new WritableCellFormat(wfTitle);	
    	
    	WritableCellFormat formateTitle=new WritableCellFormat(wcfTitle);
    	formateTitle.setAlignment(jxl.format.Alignment.CENTRE);
    	formateTitle.setVerticalAlignment(jxl.format.VerticalAlignment.CENTRE);
    	formateTitle.setBorder(jxl.format.Border.ALL,jxl.format.BorderLineStyle.THIN);
    	formateTitle.setWrap(true);
    	
    	WritableFont wfc= new WritableFont(WritableFont.ARIAL,10,WritableFont.BOLD,false,UnderlineStyle.NO_UNDERLINE,Colour.BLACK);
    	WritableCellFormat wcfFC= new WritableCellFormat(wfc);
    	//属性
    	WritableCellFormat formateHead=new WritableCellFormat(wcfFC);
    	formateHead.setAlignment(jxl.format.Alignment.CENTRE);
    	formateHead.setVerticalAlignment(jxl.format.VerticalAlignment.CENTRE);
    	formateHead.setBorder(jxl.format.Border.ALL,jxl.format.BorderLineStyle.THIN);
    	formateHead.setBackground(Colour.AQUA);
    	formateHead.setWrap(true);
    	
    	WritableCellFormat formateBody = new  WritableCellFormat(); 
    	formateBody.setAlignment(jxl.format.Alignment.LEFT);
    	formateBody.setVerticalAlignment(jxl.format.VerticalAlignment.CENTRE);
    	formateBody.setBorder(jxl.format.Border.ALL,jxl.format.BorderLineStyle.THIN);
    	formateBody.setWrap(true);
    	//创建工作薄
    	WritableWorkbook workbook = Workbook.createWorkbook(os);
    	//创建新的一页
    	WritableSheet sheet = workbook.createSheet(fname,0);
    	
    	for(int i=0;i<widths.length;i++){
    		sheet.setColumnView(i,widths[i]);
    	}
    	
    	sheet.setRowView(0,460);
    	sheet.addCell(new Label(0,0,fname,formateTitle));
    	sheet.mergeCells(0,0,colNames.length-1,0);
    	
    	sheet.setRowView(1,400);
    	int rowIndex = 1;
    	for(int i=0;i<colNames.length;i++){
    		sheet.addCell(new Label(i,rowIndex,colNames[i],formateHead));
    	}
    	for(int i=0;i<list.size();i++){
    		sheet.setRowView(++rowIndex,400);
    		Map<String, Object> obj = list.get(i);
    		sheet.addCell(new Label(0,rowIndex,(i+1)+"",formateBody));
    		for(int j=0;j<colParas.length;j++){
    			Object o = obj.get(colParas[j]);
				sheet.addCell(new Label((j+1),rowIndex,o.toString(),formateBody));
    		}
    	}
    	//把创建的内容写入到输出流中，并关闭输出流
    	workbook.write();
    	workbook.close();
    	os.close();
	}

	public String getConName() {
		return conName;
	}

	public void setConName(String conName) {
		this.conName = conName;
	}

	public String getBegTime() {
		return begTime;
	}

	public void setBegTime(String begTime) {
		this.begTime = begTime;
	}

	public String getEndTime() {
		return endTime;
	}

	public void setEndTime(String endTime) {
		this.endTime = endTime;
	}

	public String getOrderIds() {
		return orderIds;
	}

	public void setOrderIds(String orderIds) {
		this.orderIds = orderIds;
	}

	public String getStatus() {
		return status;
	}

	public void setStatus(String status) {
		this.status = status;
	}
	

}
